package midoo.server.core;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by ajianzheng on 2015/4/11.
 */
public class MChannelLimitHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(MChannelReadHandler.class);

    private int maxChannels = 100*1024;     /// default 100K

    MChannelLimitHandler(int limit) {
        this.maxChannels = limit;
    }

    public int getMaxChannels() {
        return maxChannels;
    }

    public void setMaxChannels(int maxChannels) {
        this.maxChannels = maxChannels;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        /// update channels
        if (MChannelStatistics.getInstance().addChannel(ctx) <= maxChannels) {
            ctx.fireChannelActive();
        } else {
            MServerBench.getInstance().handleOverload(MOverload.KOverloadType.CONNECTION, ctx);

            ctx.close();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        /// update channels
        MChannelStatistics.getInstance().removeChannel(ctx);
//        LOGGER.info("channelInactive:{}", ctx.channel().remoteAddress());

        ctx.channel().close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
        /// update channels
        MChannelStatistics.getInstance().removeChannel(ctx);
//        LOGGER.info("exceptionCaught:{}", ctx.channel().remoteAddress());

        ctx.channel().close();
    }
}
